<template>
  <Modal v-model="visible"
         :title="dataForm.roleId ? '编辑' : '新增'"
         :closable="false"
         :mask-closable="false">
    <Form ref="dataForm" :model="dataForm" :rules="ruleValidate" :label-width="80">
      <FormItem label="角色名称" prop="roleName">
        <Input v-model="dataForm.roleName" placeholder="输入角色名称" clearable></Input>
      </FormItem>
      <FormItem label="备注" prop="remark">
        <Input v-model="dataForm.remark" placeholder="输入备注" clearable></Input>
      </FormItem>
      <FormItem>
        <Tree ref="vTree"
              :data="menuList"
              @on-check-change="handleTreeCheck" show-checkbox multiple></Tree>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="handleCancel">取消</Button>
      <Button type="primary" :loading="showLoading" @click="handleSubmit">保存</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  data () {
    return {
      visible: false,
      showLoading: false,
      dataForm: {
        roleId: 0,
        roleName: '',
        remark: '',
        createUserId: '',
        createTime: ''
      },
      ruleValidate: {
        roleName: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ]
      },
      menuList: [],
      menuListTreeProps: {
        label: 'name',
        children: 'children'
      },
      menuAll: [],
      tempKey: -999
    }
  },
  methods: {
    init (id) {
      // add or update
      this.$refs['dataForm'].resetFields();
      this.visible = true;
      this.dataForm.roleId = id || 0;
      this.$http({
        url: this.$http.adornUrl('/sys/menu/list'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.menuAll = data;
      }).then(() => {
        if (this.dataForm.roleId) {
          // 根据主键获取详情
          let url = '/sys/role/info/' + this.dataForm.roleId;
          this.$http({
            url: this.$http.adornUrl(url),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.roleName = data.role.roleName;
              this.dataForm.remark = data.role.remark;
              /* */
              let idx = data.role.menuIdList.indexOf(this.tempKey);
              if (idx !== -1) {
                data.role.menuIdList.splice(idx, data.role.menuIdList.length - idx);
              }
              data.role.menuIdList.forEach((item) => {
                this.menuAll.filter((node) => {
                  if (item === node.menuId) {
                    node.checked = true;
                  }
                })
              });
              this.menuList = this.vTreeDataTranslate(this.menuAll, 'menuId');
            }
          });
        } else {
          this.menuList = this.vTreeDataTranslate(this.menuAll, 'menuId');
        }
      });
    },
    handleCancel () {
      this.visible = false;
      this.showLoading = false;
    },
    handleSubmit () { // 表单提交
      let url = '/sys/role/' + (this.dataForm.roleId ? 'update' : 'save');
      // let temp = this.$refs.rTree.getCheckedKeys();
      let temp = [];
      let checkIds = [];
      this.$refs.vTree.getCheckedNodes().forEach((item) => {
        temp.push(item.menuId);
      });
      temp.forEach((item) => {
        /* */
        let arr = this.getCheckNodes(this.menuAll, item);
        checkIds = checkIds.concat(arr);
      });
      // 去重
      checkIds = Array.from(new Set(checkIds));

      let param = {
        'roleId': this.dataForm.roleId || undefined,
        'roleName': this.dataForm.roleName,
        'remark': this.dataForm.remark,
        'menuIdList': [].concat(temp, [this.tempKey], checkIds)
      };
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.showLoading = true;
          this.$http({
            url: this.$http.adornUrl(url),
            method: 'post',
            data: this.$http.adornData(param)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$Message.success({
                content: '操作成功',
                duration: 2,
                onClose: () => {
                  this.handleCancel();
                  this.$emit('refreshDataList')
                }
              });
            } else {
              this.$Message.error(data.msg);
              this.showLoading = false;
            }
          })
        }
      })
    },
    handleTreeCheck () {
      // let nodes = this.$refs.vTree.getCheckedNodes();
    },
    getCheckNodes (menuList = [], menuId = 0, menuIdList = []) {
      let selfNode = menuList.filter((item) => menuId === item.menuId)[0];
      if (selfNode && menuIdList.indexOf(selfNode.parentId) === -1) {
        if (selfNode.parentId !== 0) {
          menuIdList.push(selfNode.parentId);
          this.getCheckNodes(menuList, selfNode.parentId, menuIdList);
        }
      }
      return menuIdList;
    },
    vTreeDataTranslate (data, id = 'id', pid = 'parentId') {
      let res = [];
      let temp = {};
      for (let i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i];
      }
      for (let k = 0; k < data.length; k++) {
        data[k]['title'] = data[k]['name'];
        // data[k]['expand'] = true;
        // data[k]['checked'] = false;
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
          if (!temp[data[k][pid]]['children']) {
            temp[data[k][pid]]['children'] = [];
          }
          if (!temp[data[k][pid]]['_level']) {
            temp[data[k][pid]]['_level'] = 1;
          }
          data[k]['_level'] = temp[data[k][pid]]._level + 1;
          temp[data[k][pid]]['children'].push(data[k]);
        } else {
          res.push(data[k]);
        }
      }
      return res;
    }
  }
}
</script>
